package com.redis.midengxing;


import com.redis.midengxing.zhujie.MdxApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;

/**
 * 作者: LCG
 * 日期: 2020/7/6 23:23
 * 描述:
 */
@Component
public class MyMdxIntercepter extends HandlerInterceptorAdapter {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        //转为拦截辅助方法
        HandlerMethod handlerMethod=(HandlerMethod)handler;

        //获取当前拦截的方法上的注解信息
        MdxApi methodAnnotation = handlerMethod.getMethodAnnotation(MdxApi.class);

        String code = request.getParameter("code");

        if(methodAnnotation==null){
            //直接放行
            return super.preHandle(request, response, handler);
        }else{
            //校验幂等性
            if(checkCode(code)){
                return super.preHandle(request, response, handler);
            }else{
                response.getOutputStream().print("{error}");
                return false;
            }
        }

    }

    /**
     * 检测请求中携带的参数
     * @return
     */
    public boolean checkCode(String code){

        String lua="if redis.call('get',KEYS[1]) then return redis.call('del',KEYS[1]) else return 0 end";

        DefaultRedisScript<Long> defaultRedisScript=new DefaultRedisScript<>();
        defaultRedisScript.setResultType(Long.class);
        defaultRedisScript.setScriptText(lua);

        Long execute = redisTemplate.execute(defaultRedisScript, Collections.singletonList(code));

        if(execute==1){
            return true;
        }else{
            return false;
        }

    }
}
